package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.account.util.BankAssoc;
import com.turing.post.account.util.BankAssocDao;
import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.cardmanagement.util.AppManTranBusinessAgent;
import com.turing.post.cardmanagement.util.AppManagement;
import com.turing.post.cardmanagement.util.AppManagementDao;
import com.turing.post.cardmanagement.util.CardATS;
import com.turing.post.cardmanagement.util.CardATSDao;
import com.turing.post.cardmanagement.util.CardFace;
import com.turing.post.cardmanagement.util.CardFaceDao;
import com.turing.post.cardmanagement.util.CardStock;
import com.turing.post.cardmanagement.util.CardStockDao;
import com.turing.post.cardmanagement.util.MakeCardControl;
import com.turing.post.cardmanagement.util.MakeCardControlDao;
import com.turing.post.cardtransactions.util.SaleTransBusiness;
import com.turing.post.organization.util.BankManage;
import com.turing.post.organization.util.BankTranBusinessAgent;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.salesmanage.util.GasAutoManagement;
import com.turing.post.salesmanage.util.GasAutoManagementBusiness;
import com.turing.post.salesmanage.util.GasAutoManagementDao;
import com.turing.post.salesmanage.util.OrganizeCustomDao;
import com.turing.post.salesmanage.util.PersonalCustom;
import com.turing.post.salesmanage.util.PersonalCustomDao;
import com.turing.post.salesmanage.util.SaleOrder;
import com.turing.post.salesmanage.util.SaleOrderBusiness;
import com.turing.post.salesmanage.util.SaleOrderCardDetail;
import com.turing.post.salesmanage.util.SaleOrderPaidDetail;
import com.turing.post.salesmanage.util.SaleOrderRealNameDetail;
import com.turing.post.salesmanage.util.SalesManageApplicationException;
import com.turing.post.salesmanage.util.SalesManageRespCode;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * 燃气汽车卡管理信息业务实现
 * 
 * @author zxp
 * @Apr 9, 2013
 */
@Stateless(mappedName = "salesmanage.impl.GasAutoManagementBusinessImpl")
@Remote
@Local
public class GasAutoManagementBusinessImpl implements GasAutoManagementBusiness {

	@EJB(mappedName = "cardmanagement.impl.AppManagementDaoImpl")
	private AppManagementDao appManagementDaoImpl;

	@EJB(mappedName = "salesmanage.impl.SaleOrderBusinessImpl")
	private SaleOrderBusiness saleOrderBusinessImpl;

	@EJB(mappedName = "salesmanage.impl.GasAutoManagementDaoImpl")
	private GasAutoManagementDao gasAutoManagementDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao sysBranchDaoImpl;

	@EJB(mappedName = "account.impl.BankAssocDaoImpl")
	private BankAssocDao bankAssocDaoImpl;

	@EJB(mappedName = "salesmanage.impl.PersonalCustomDaoImpl")
	private PersonalCustomDao personalCustomDaoImpl;

	@EJB(mappedName = "salesmanage.impl.OrganizeCustomDaoImpl")
	private OrganizeCustomDao organizeCustomDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardStockDaoImpl")
	private CardStockDao cardStockDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardATSDaoImpl")
	private CardATSDao cardATSDaoImpl;

	@EJB(mappedName = "cardtransactions.impl.SaleTransBusinessImpl")
	private SaleTransBusiness saleTransBusinessImpl;

	@EJB(mappedName = "cardmanagement.impl.MakeCardControlDaoImpl")
	private MakeCardControlDao makeCardControlDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardFaceDaoImpl")
	private CardFaceDao cardFaceDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao acDao;

	/**
	 * 异常抛出方法
	 * 
	 * @param error
	 * @throws PCPSApplicationException
	 */
	@SuppressWarnings("unused")
	private void errException(String error) throws PCPSApplicationException {
		throw new SalesManageApplicationException(
				SalesManageApplicationException.ERRCODE_CATEGORY_APPLICATION,
				SalesManageRespCode.SALESBUSINESS_ARGS_NULL, error);
	}

	@Override
	public String[] createGasAutoManagement(PCPSWebInput input,
			GasAutoManagement gamg, BankAssoc ba, SaleOrder saleOrder,
			List<SaleOrderCardDetail> cardDetailList,
			List<SaleOrderPaidDetail> paidDetailList)
			throws PCPSApplicationException {
		if (input == null || PCPSUtil.isEmpty(input.getOperBranchNo())
				|| input.getOperId() == null) {
			errException("登录用户编号或归属机构为空!");
		}

		if (PCPSUtil.isEmpty(gamg.getVIN())) {
			errException("车架号为空!");
		}

		if (PCPSUtil.isEmpty(gamg.getCardNo())) {
			errException("卡号为空!");
		}
		if (saleOrder.getPersonalBuyerId() == null) {
			errException("购卡人不可为空!");
		}
		List<CardATS> ats = cardATSDaoImpl.getCardATSByCardNo(gamg.getCardNo());
		if (ats == null || ats.size() < 1) {
			errException("卡号" + gamg.getCardNo() + "未预处理!");
		}
		if (ba.getBankManageId() == null || PCPSUtil.isEmpty(ba.getAccNo())) {
			errException("未选定银行或银行账号为空!");
		}
		if (cardDetailList == null || cardDetailList.size() != 1) {
			errException("燃气应用每次只可售一张卡!");
		}

		SysBranch sb = sysBranchDaoImpl.getSysBranchByBranchNo(input
				.getOperBranchNo());
		if (!sb.getBranchType().equals(SysBranch.SYSBRANCH_SALEBRANCH)) {
			errException("非销售商机构操作员，禁止售卡!");
		}

		AppManagement am = appManagementDaoImpl
				.getAppManagementByAID(AppManagement.AppManagement_Gas);
		if (am == null) {
			errException("燃气车加气卡应用编号“" + AppManagement.AppManagement_Gas
					+ "”系统中不存在!");
		}
		if (am.getActivate().equals(AppManagement.AppManagement_NoActivate)) {
			errException("燃气车加气卡应用未激活!");
		}

		gamg.setAppId(am.getAppId());// 应用管理ID

		String buyName = "";
		SaleOrderRealNameDetail sornd = new SaleOrderRealNameDetail();
		PersonalCustom pc = personalCustomDaoImpl
				.getPersonalCustomByPersonalId(saleOrder.getPersonalBuyerId());
		if (saleOrder.getBuyerType().equals(
				SaleOrder.SaleOrder_BuyerType_Person)) {
			sornd.setCustomId(saleOrder.getPersonalBuyerId());
			buyName = pc.getName();
		} else if (saleOrder.getBuyerType().equals(
				SaleOrder.SaleOrder_BuyerType_company)) {
			if (saleOrder.getProxyBuyerId() == null) {
				errException("单位购卡必须填写代理人!");
			}
			buyName = organizeCustomDaoImpl.getOrganizeCustomByOrganizeId(
					saleOrder.getOrganizeBuyerId()).getFullName();
			sornd.setCustomId(saleOrder.getProxyBuyerId());
		}
		
		// 设置购卡人实名
		List<SaleOrderRealNameDetail> realNameList = new ArrayList<SaleOrderRealNameDetail>();
		CardStock cs = cardStockDaoImpl.getCardStockByCardNoForUpdate(gamg
				.getCardNo());
		if (cs == null || PCPSUtil.isEmpty(cs.getBatchNo())) {
			errException("未在卡库存中找到该卡" + gamg.getCardNo());
		}

		sornd.setBatchNo(cs.getBatchNo());
		sornd.setCardSeqNo(cs.getCardSeqNo());
		sornd.setIdNo(pc.getIdNo());
		sornd.setName(pc.getName());
		sornd.setCardNo(gamg.getCardNo());
		realNameList.add(sornd);
	
		// 调用三环接口验证
		gamg = (GasAutoManagement) AppManTranBusinessAgent.AppCardIssuePre(am,
				buyName, gamg);
		
		MakeCardControl mcc = makeCardControlDaoImpl
				.getMakeCardControlByBatchNo(cs.getBatchNo());
		CardFace cf = cardFaceDaoImpl.getCardFaceByCardFaceId(mcc
				.getCardFaceId());
		if (!cf.getMediaType().equals(CardFace.CARDFACE_MEDIATYPE_CPU)) {
			errException("不可销售非CPU多界面卡!");
		}
		// 封装销售单卡明细
		SaleOrderCardDetail socd = cardDetailList.get(0);
		socd.setBatchNo(cs.getBatchNo());// 售卡批次,比填项
		socd.setStartCardSeqNo(cs.getCardSeqNo());
		socd.setEndCardSeqNo(cs.getCardSeqNo());
		socd.setInitDeposit(0);// 卡面值
		socd.setCardCount(1);// 卡张数
		List<SaleOrderCardDetail> _cardDetailList = new ArrayList<SaleOrderCardDetail>();
		_cardDetailList.add(socd);
		
		// 销售单押金
		saleOrder.setDepositFee(BigInteger.ZERO);
		SaleOrder so = saleOrderBusinessImpl.createSaleOrder(input, saleOrder,
				_cardDetailList, null, realNameList, paidDetailList);

		String cardNo = gamg.getCardNo();
		gasAutoManagementDaoImpl.insert(gamg);

		// 调用销售单激活流程
		saleTransBusinessImpl.activateAppManageSaleOrder(so.getSaleOrderId(),
				input.getOperId());
		// 售卡创建主账号钱包账号
		ActivateCard ac = acDao.getActivateCardByCardNo(cardNo);
		BigInteger masterAccNo = ac.getMasterAccNo();
		// 插入关联表
		ba.setMasterAccNo(masterAccNo);// 主账号
		bankAssocDaoImpl.insert(ba);

		// 调用卡发行APDU指定接口 传入 AppManagement_Gas
		return new String[] { "PBSE", "AXCT" };
	}

	// 写卡成功后 调用双方接口
	// 调用邮储接口签约
	// 传入：主账号、邮储个人结算账号、类型、姓名、证件类型、证件证号
	// 调用三环接口开卡注册
	@Override
	public void updateThirdSystem(PCPSWebInput input, GasAutoManagement gamg,
			BankAssoc ba, BankManage bm) throws PCPSApplicationException {
		if (input == null || PCPSUtil.isEmpty(input.getOperBranchNo())
				|| input.getOperId() == null) {
			errException("登录用户编号或归属机构为空!");
		}
		if (PCPSUtil.isEmpty(gamg.getCardNo())) {
			errException("卡号为空!");
		}
		if (bm == null || bm.getBankManageId() == null
				|| bm.getBankManageId().intValue() == 0) {
			errException("银行管理编号为空!");
		}
		if (ba == null || PCPSUtil.isEmpty(ba.getAccNo())) {
			errException("邮储个人结算账号为空!");
		}
		AppManagement am = appManagementDaoImpl
				.getAppManagementByAID(AppManagement.AppManagement_Gas);
		if (am == null) {
			errException("燃气车加气卡应用编号“" + AppManagement.AppManagement_Gas
					+ "”系统中不存在!");
		}
		if (am.getActivate().equals(AppManagement.AppManagement_NoActivate)) {
			errException("燃气车加气卡应用未激活!");
		}
		gamg.setAppId(am.getAppId());
		GasAutoManagement _gamg = gasAutoManagementDaoImpl
				.getGasAutoManagementByPk(gamg);
		if (_gamg == null) {
			errException("系统中不存在卡“" + gamg.getCardNo() + "”开卡记录!");
		}
		// 调用三环接口更新三环系统数据
		AppManTranBusinessAgent.AppCardIssuePost(am, _gamg.getCardNo(), _gamg);

		BankTranBusinessAgent.BankCardIssuePre(bm, gamg.getCardNo(), null);
	}
}
